import { getSearchList, ISuggestList } from "@/services/modules/home";
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { HYDRATE } from "next-redux-wrapper";
interface IHomeIState {
  count: number;
  sugList?: ISuggestList;
}
const homeStore = createSlice({
  name: "home",
  initialState: {
    count: 0,
    sugList: {},
  } as IHomeIState,
  reducers: {
    increment(state, { payload }) {
      state.count += payload;
    },
    setSuggestList(state, { payload }) {
      state.sugList = payload;
    },
  },
  extraReducers: (builder) => {
    builder.addCase(HYDRATE, (state, action: any) => {
      return {
        ...state,
        ...action.payload.home,
      };
    });
    // .addCase(fetchSuggestList.fulfilled, (state, { payload }) => {
    //   state.sugList = payload;
    // });
  },
});

// 异步函数
export const fetchSuggestList = createAsyncThunk(
  "fetchSuggestList",
  async (params: any, { dispatch }) => {
    const res = await getSearchList();
    if (res.code === 200) {
      dispatch(homeStore.actions.setSuggestList(res.data));
      // console.log(res.data);
    }
    return res.data;
  }
);

// 导出同步函数
export const { increment } = homeStore.actions;
export default homeStore.reducer;
